import { SearchOutlined } from '@ant-design/icons';
import {
  Button,
  Input,
  type InputRef,
  Space,
  Table,
  type TableColumnType,
  type TableColumnsType,
} from 'antd';
import type { FilterDropdownProps } from 'antd/es/table/interface';
import { useCallback, useEffect, useRef, useState } from 'react';
import type * as React from 'react';
import Highlighter from 'react-highlight-words';
import AddCustomerModal from './AddCustomerModal';
import AdminCustomerModal from './AdminCustomerModal';

interface DataType {
  key: React.Key;
  customerID: number;
  customerName: string;
  PID: string;
  telephone: string;
  address: string;
}

type DataIndex = keyof DataType;

function AdminCustomer() {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState<DataType | null>(
    null,
  );
  const [customers, setCustomers] = useState<DataType[]>([]);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef<InputRef>(null);

  const handleSearch = (
    selectedKeys: string[],
    confirm: FilterDropdownProps['confirm'],
    dataIndex: DataIndex,
  ) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters: () => void) => {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (
    dataIndex: DataIndex,
  ): TableColumnType<DataType> => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
      close,
    }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          placeholder={`搜索 ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            handleSearch(selectedKeys as string[], confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() =>
              handleSearch(selectedKeys as string[], confirm, dataIndex)
            }
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              setSearchText((selectedKeys as string[])[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
    filterDropdownProps: {
      onOpenChange(open) {
        if (open) {
          setTimeout(() => searchInput.current?.select(), 100);
        }
      },
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const columns: TableColumnsType<DataType> = [
    {
      title: '客户ID',
      dataIndex: 'customerID',
      sorter: (a, b) => a.customerID - b.customerID,
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      ...getColumnSearchProps('customerName'),
    },
    {
      title: '身份证号',
      dataIndex: 'PID',
      width: '20%',
      ...getColumnSearchProps('PID'),
    },
    {
      title: '电话',
      dataIndex: 'telephone',
      ...getColumnSearchProps('telephone'),
    },
    {
      title: '地址',
      dataIndex: 'address',
      ...getColumnSearchProps('address'),
    },
  ];

  const fetchCustomers = useCallback(() => {
    fetch('http://localhost:8000/customers/')
      .then((response) => response.json())
      .then((data) => {
        const formattedData = data.map((customer: any) => ({
          key: customer.customerID,
          customerID: customer.customerID,
          customerName: customer.customerName,
          PID: customer.PID,
          telephone: customer.telephone,
          address: customer.address,
        }));
        setCustomers(formattedData);
      });
  }, []);

  useEffect(() => {
    fetchCustomers();
  }, [fetchCustomers]);

  const handleRowClick = (record: DataType) => {
    setSelectedCustomer(record);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedCustomer(null);
  };

  const handleOperationSuccess = () => {
    fetchCustomers();
    setIsModalVisible(false);
    setIsAddModalVisible(false);
  };

  return (
    <>
      <Button
        type="primary"
        style={{ marginBottom: 16 }}
        onClick={() => setIsAddModalVisible(true)}
      >
        新增客户
      </Button>
      <Table<DataType>
        columns={columns}
        dataSource={customers}
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
      />
      {selectedCustomer && (
        <AdminCustomerModal
          visible={isModalVisible}
          onCancel={handleCancel}
          customer={selectedCustomer}
          onSuccess={handleOperationSuccess}
        />
      )}
      <AddCustomerModal
        visible={isAddModalVisible}
        onCancel={() => setIsAddModalVisible(false)}
        onSuccess={handleOperationSuccess}
      />
    </>
  );
}

export default AdminCustomer;
